﻿using AutoMapper;
using MediatR;
using S.Services.SheepMale.Api.Application.Command.PurchaseCommand;
using S.Services.SheepMale.Domain.PurchaseSales;
using S.Services.SheepMale.Infrastructure;

namespace S.Services.SheepMale.Api.Application.CommandHandler.PurchaseCommandHandler
{
    public class PurchaseAddCommandHandler : IRequestHandler<PurchaseAddCommand, int>
    {
        private readonly IRepository<EntityPurchase> repository;

        private readonly IMapper mapper;

        public PurchaseAddCommandHandler(IRepository<EntityPurchase> repository, IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 采购添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(PurchaseAddCommand request, CancellationToken cancellationToken) 
        { 
        
            var result = repository.AllAsync().Result.Where(x => x.Earbugles == request.Earbugles&&x.DocumentNumber==request.DocumentNumber);
            if (result.Count() != 0)
            {
                return -1;
            }
            request.ExamineType = true;
            request.CreateDate = DateTime.Now;
            return await repository.CreateAsync(mapper.Map<EntityPurchase>(request));
        }
    }
}
